package com.gitee.cirnochat.user.service.strategy.impl;


import com.gitee.cirnochat.common.model.dto.NoticeMessage;
import com.gitee.cirnochat.common.model.dto.payload.FriendOfflinePayload;
import com.gitee.cirnochat.common.model.enums.SystemNoticeType;
import com.gitee.cirnochat.user.model.entity.Friend;
import com.gitee.cirnochat.user.service.FriendService;
import com.gitee.cirnochat.user.service.strategy.UserStateStrategy;
import com.gitee.cirnochat.websocket.model.dto.WebSocketUserMessage;
import com.gitee.cirnochat.websocket.service.WebSocketService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

import static com.gitee.cirnochat.common.constant.RedisKey.USER_LAST_ONLINE_KEY;
import static com.gitee.cirnochat.common.constant.WebSocketConstant.CHAT_SYSTEM_CHANNEL;

@Component
@RequiredArgsConstructor
@Slf4j
public class UserHiddenStateStrategy implements UserStateStrategy {
    private final FriendService friendService;
    private final WebSocketService webSocketService;
    private final StringRedisTemplate redisTemplate;

    @Override
    public void execute(Long userId) {
        log.info("用户 {} 隐身", userId);
        sendOfflineNoticeToFriend(userId);
    }


    /**
     * 发送离线通知给好友
     * @param userId 离线的用户ID
     */
    private void sendOfflineNoticeToFriend(Long userId) {
        // 获取上次的离线时间
        String offlineTime = redisTemplate.opsForValue().get(USER_LAST_ONLINE_KEY + userId);

        // 构建离线通知消息
        final FriendOfflinePayload friendOfflinePayload = new FriendOfflinePayload();
        friendOfflinePayload.setFriendId(userId);
        friendOfflinePayload.setOfflineTime(offlineTime != null ? LocalDateTime.parse(offlineTime) : null);

        final NoticeMessage<FriendOfflinePayload> payload = new NoticeMessage<>();
        payload.setPayload(friendOfflinePayload);
        payload.setType(SystemNoticeType.FRIEND_OFFLINE_NOTICE);

        // 获取用户的所有好友
        List<Friend> friends = friendService.getFriends(userId);

        // 对所有好友发送在线通知
        for (Friend friend : friends) {
            webSocketService.sendMessageToOnlineDevices(new WebSocketUserMessage(friend.getFriendId().toString(), CHAT_SYSTEM_CHANNEL,  payload));
        }
    }
}
